package org.example.project.common.validator;

import org.example.project.common.util.RegExUtils;
import org.example.project.common.validator.annotation.Mobile;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author wenxy
 * @date 2020/10/12
 */
public class MobileValidator implements ConstraintValidator<Mobile, String> {

    Pattern pattern = Pattern.compile(RegExUtils.MOBILE);

    boolean required;

    @Override
    public void initialize(Mobile constraintAnnotation) {
        required = constraintAnnotation.isRequired();

        if (!StringUtils.isBlank(constraintAnnotation.regexp())) {
            pattern = Pattern.compile(constraintAnnotation.regexp());
        }
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required && StringUtils.isBlank(value)) {
            return true;
        }

        if (StringUtils.isBlank(value)) {
            return false;
        }

        return pattern.matcher(value).matches();
    }

}
